import Vue from 'vue'
import VueRouter, { RouteConfig } from 'vue-router'
import HomeView from '../views/HomeView.vue'

Vue.use(VueRouter)

const routes: Array<RouteConfig> = [
  {
    path: '/home',
    name: 'home',
    component: HomeView,
    // redirect: '/home/studentinfo',
    children: [
      {
        path: '/home/studentinfo',
        name: 'studentinfo',
        component: () => import('../views/StudentInfo.vue')
      },
      {
        path: '/home/classchoice',
        name: 'classchoice',
        component: () => import('../views/ClassChoice.vue')
      },
      {
        path: '/home/classmanage',
        name: 'classmanage',
        component: () => import('../views/ClassManage.vue')
      },
      {
        path: '/home/gradeinfo',
        name: 'gradeinfo',
        component: () => import('../views/GradeInfo.vue')
      },
      {
        path: '/home/grademanage',
        name: 'grademanage',
        component: () => import('../views/GradeManage.vue')
      }
    ]
  },
  {
    path: '/about',
    name: 'about',
    component: () => import(/* webpackChunkName: "about" */ '../views/AboutView.vue')
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/LoginView.vue')
  },
  {
    path: '/404',
    component: () => import('../views/404View.vue')
  },
  {
    path: '*',
    // 重定向
    redirect: '/404'
  }
]

const router = new VueRouter({
  routes
})

// 路由守卫 检查是否已登录
router.beforeEach((to, from, next) => {
  const isLoggedIn = !!sessionStorage.getItem('authToken') // 检查 authToken 是否存在
  const userPower = sessionStorage.getItem('userPower') // 获取用户权

  if (!isLoggedIn && to.name !== 'login') {
    next({ name: 'login' }) // 如果未登录并且不是去登录页面，则重定向到登录页面
  } else if (to.name === 'studentinfo' || to.name === 'classmanage' || to.name === 'grademanage') {
    // 权限为teacher的用户可以访问这些页面
    if (userPower === 'teacher') {
      next()
    } else {
      alert('您没有权限访问此页面')
      next(false) // 阻止导航
    }
  } else if (to.name === 'classchoice' || to.name === 'gradeinfo') {
    // 权限为student的用户可以访问这些页面
    if (userPower === 'student') {
      next()
    } else {
      alert('您没有权限访问此页面')
      next(false) // 阻止导航
    }
  } else {
    next() // 允许进入其他页面或继续导航
  }
})

export default router
